<template>
  <div class="goods-item" @click="itemClick">
    <img :src="showImage" alt="" @load="imageLoad">
    <div class="goods-info">
      <p>{{goodsItem.title}}</p>
      <span class="price">{{goodsItem.price}}</span>
      <span class="collect">{{goodsItem.cfav}}</span>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'GoodsListItem',
    props: {
      goodsItem: {
        type: Object,
        default() {
          return {}
        }
      }
    },
    computed: {
      showImage() {
        return this.goodsItem.image || this.goodsItem.show.img;
      }
    },
    methods: {
      imageLoad() {
        this.$bus.$emit('itemImgLoad') // 发出事件总线，与Home/Detail组件通信

        // 由于此组件被首页与详情页复用，对详情页进行操作时会影响首页。所以二者要单独区分开
        // 方式一：通过路由区分
        // if (this.$route.path.indexOf('/home')) {
        //   this.$bus.$emit('homeItemImgLoad')
        // } else if (this.$route.path.indexOf('/detail')) {
        //   this.$bus.$emit('detailItemImgLoad')
        // }

        // 方式二：首页在不被激活、详情页在被销毁时取消对事件总线的监听
        // this.$bus.$off('itemImgLoad', this.itemImgListener)
        // 混入：将公共代码抽取到common/mixin.js中
      },
      itemClick() {
        // this.$router.push('/detail/' + this.goodsItem.iid)
        this.$router.push({
          path: '/detail',
          query: {
            iid: this.goodsItem.iid
          }
        })
      }
    }
  }
</script>

<style scoped>
  .goods-item {
    position: relative;
    width: 48%;
    padding-bottom: 40px;
  }

  .goods-item img {
    width: 100%;
    border-radius: 5px;
  }

  .goods-info {
    position: absolute;
    bottom: 5px;
    left: 0;
    right: 0;
    text-align: center;
    font-size: 12px;
    overflow: hidden;
  }

  .goods-info p {
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    margin-bottom: 3px;
  }

  .goods-info .price {
    margin-right: 20px;
    color: var(--color-high-text);
  }

  .goods-info .collect {
    position: relative;
  }

  .goods-info .collect::before {
    content: '';
    position: absolute;
    left: -15px;
    top: -1px;
    width: 14px;
    height: 14px;
    background: url("~assets/img/common/collect.svg") no-repeat;
    background-size: 14px 14px;
  }
</style>
